<template>
    <div class="account-page">
        <el-card class="account-card">
            <div class="header">
                <span class="title">账号管理</span>
                <el-button
                    type="primary"
                    @click="showAddDialog = true"
                    size="large"
                    round
                >
                    添加用户
                </el-button>
            </div>
            <!-- 筛选区域 -->
            <div
                style="
                    display: flex;
                    gap: 16px;
                    align-items: center;
                    margin-bottom: 16px;
                "
            >
                <el-input
                    v-model="searchAccount"
                    placeholder="筛选账号"
                    clearable
                    style="width: 180px"
                />
                <el-input
                    v-model="searchName"
                    placeholder="筛选姓名"
                    clearable
                    style="width: 180px"
                />
            </div>
            <el-table
                :data="pagedUsers"
                style="width: 100%; margin-top: 24px"
                border
            >
                <el-table-column prop="account" label="账号" width="180" />
                <el-table-column prop="name" label="姓名" width="180" />
                <el-table-column prop="position" label="职位" width="180" />
                <el-table-column label="操作" width="220">
                    <template #default="scope">
                        <el-button
                            size="small"
                            @click="openEdit(scope.row)"
                            round
                            :disabled="
                                myPosition === '管理员' &&
                                scope.row.position === '社长'
                            "
                            >编辑</el-button
                        >
                        <el-popconfirm
                            title="确定删除该用户吗？"
                            @confirm="deleteUser(scope.row._id)"
                            confirm-button-text="删除"
                            cancel-button-text="取消"
                            :disabled="
                                myPosition === '管理员' &&
                                scope.row.position === '社长'
                            "
                        >
                            <template #reference>
                                <el-button
                                    size="small"
                                    type="danger"
                                    round
                                    :disabled="
                                        myPosition === '管理员' &&
                                        scope.row.position === '社长'
                                    "
                                    >删除</el-button
                                >
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; margin: 24px 0">
                <el-pagination
                    :page-size="20"
                    :total="filteredUsers.length"
                    v-model:current-page="currentPage"
                    layout="prev, pager, next"
                />
            </div>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog
            v-model="showAddDialog"
            title="添加用户"
            width="400px"
            :close-on-click-modal="false"
            center
        >
            <el-form :model="addForm" label-width="80px">
                <el-form-item label="账号">
                    <el-input v-model="addForm.account" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input
                        v-model="addForm.password"
                        type="password"
                        autocomplete="off"
                    />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="addForm.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="职位">
                    <el-select
                        v-model="addForm.position"
                        placeholder="请选择职位"
                    >
                        <el-option
                            v-for="item in positionOptions"
                            :key="item"
                            :label="item"
                            :value="item"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showAddDialog = false">取消</el-button>
                <el-button type="primary" @click="addUser" :loading="addLoading"
                    >添加</el-button
                >
            </template>
        </el-dialog>

        <!-- 编辑用户对话框 -->
        <el-dialog
            v-model="showEditDialog"
            title="编辑用户"
            width="400px"
            :close-on-click-modal="false"
            center
        >
            <el-form :model="editForm" label-width="80px">
                <el-form-item label="账号">
                    <el-input
                        v-model="editForm.account"
                        autocomplete="off"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="editForm.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="职位">
                    <el-select
                        v-model="editForm.position"
                        placeholder="请选择职位"
                    >
                        <el-option
                            v-for="item in positionOptions"
                            :key="item"
                            :label="item"
                            :value="item"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input
                        v-model="editForm.password"
                        type="password"
                        autocomplete="off"
                        placeholder="不修改请留空"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="updateUser"
                    :loading="editLoading"
                    >保存</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
    getAllUsers,
    getUserById,
    addUserApi,
    updateUserApi,
    deleteUserApi,
} from "./api";
import { BASE_URL } from "../config/http.js";

// 用户列表
const users = ref([]);
// 筛选相关
const searchAccount = ref("");
const searchName = ref("");
const currentPage = ref(1);
const pageSize = 20;

const filteredUsers = computed(() => {
    return users.value.filter(
        (item) =>
            (!searchAccount.value ||
                (item.account || "")
                    .toLowerCase()
                    .includes(searchAccount.value.toLowerCase())) &&
            (!searchName.value ||
                (item.name || "")
                    .toLowerCase()
                    .includes(searchName.value.toLowerCase()))
    );
});
const pagedUsers = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return filteredUsers.value.slice(start, start + pageSize);
});
// 添加用户
const showAddDialog = ref(false);
const addForm = reactive({
    account: "",
    password: "",
    name: "",
    position: "",
});
const addLoading = ref(false);

// 编辑用户
const showEditDialog = ref(false);
const editForm = reactive({
    _id: "",
    account: "",
    name: "",
    position: "",
    password: "",
});
const editLoading = ref(false);

// 职位选项
const positionOptions = ref(["社员"]);
const myPosition = ref("");

function setPositionOptions() {
    const userId = sessionStorage.getItem("user_id");
    if (userId) {
        getUserById(userId).then((data) => {
            myPosition.value = data.position;
            if (myPosition.value === "社长") {
                positionOptions.value = ["管理员", "社员"];
            } else if (myPosition.value === "管理员") {
                positionOptions.value = ["社员"];
            } else {
                positionOptions.value = [];
            }
        });
    }
}

// 获取所有用户
function fetchUsers() {
    const requesterId = sessionStorage.getItem("user_id");
    getAllUsers(requesterId).then((res) => {
        users.value = res;
    });
}

function addUser() {
    if (
        !addForm.account ||
        !addForm.password ||
        !addForm.name ||
        !addForm.position
    ) {
        ElMessage.warning("请填写完整信息");
        return;
    }
    addLoading.value = true;
    const creatorId = sessionStorage.getItem("user_id");
    addUserApi({ ...addForm, creatorId })
        .then(() => {
            ElMessage.success("添加成功");
            showAddDialog.value = false;
            Object.assign(addForm, {
                account: "",
                password: "",
                name: "",
                position: "",
            });
            fetchUsers();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "添加失败");
        })
        .finally(() => {
            addLoading.value = false;
        });
}

function openEdit(row) {
    Object.assign(editForm, row, { password: "" });
    showEditDialog.value = true;
}

function updateUser() {
    if (!editForm.name || !editForm.position) {
        ElMessage.warning("请填写完整信息");
        return;
    }
    editLoading.value = true;
    const updaterId = sessionStorage.getItem("user_id");
    const updateData = {
        name: editForm.name,
        position: editForm.position,
        updaterId,
    };
    if (editForm.password) updateData.password = editForm.password;
    updateUserApi(editForm._id, updateData)
        .then(() => {
            ElMessage.success("更新成功");
            showEditDialog.value = false;
            fetchUsers();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "更新失败");
        })
        .finally(() => {
            editLoading.value = false;
        });
}

function deleteUser(id) {
    const deleterId = sessionStorage.getItem("user_id");
    deleteUserApi(id, deleterId)
        .then(() => {
            ElMessage.success("删除成功");
            fetchUsers();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "删除失败");
        });
}

onMounted(() => {
    fetchUsers();
    setPositionOptions();
});
</script>


<style lang="scss" scoped>
.account-page {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    min-height: 80vh;
    padding: 40px 0;
    background: transparent;
}
.account-card {
    width: 1000px;
    border-radius: 32px;
    box-shadow: 0 8px 32px 0 rgba(60, 60, 120, 0.12);
    padding: 32px 36px 36px 36px;
    background: #fff;
    animation: mainPop 0.7s cubic-bezier(0.55, 0, 0.1, 1);
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}
.title {
    font-size: 2rem;
    font-weight: bold;
    color: #409eff;
    letter-spacing: 2px;
}
</style>